package com.witsight.hibernate.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;

import org.hibernate.engine.spi.NamedQueryDefinition;
import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.query.spi.NamedQueryRepository;
import org.springframework.beans.factory.annotation.Autowired;

/**   
 * 说明：使用者实现自己Dao是需要继承这个抽象类
 *      所有的Dao必须都继承这个抽象类
 * @Title: BaseJpaRepositoryImpl.java 
 * @Package com.witsight.hibernate.dao 
 * @See: {@link #BaseJpaRepositoryImpl()}
 * Copyright: Copyright (c) 2017
 * Company:sany huax witsight team by product
 * @author: fuyp  
 * @date: 2017年9月18日 下午4:17:30 
 * @version: V1.0
 *
 */
public abstract class BaseJpaRepositoryImpl {
	@PersistenceContext
	private EntityManager em;	
	@Autowired
	private EntityManagerFactory entityManagerFactory;

	public EntityManager getEm() {
		return em;
	}
	public EntityManagerFactory getSessionFactory() {
		return entityManagerFactory;
	}

	private NamedQueryRepository getNamedQueryRepository() {
		NamedQueryRepository namedQueryRepository = null;
		Object sessionFactory = entityManagerFactory.createEntityManager().getEntityManagerFactory();
		if (sessionFactory instanceof SessionFactoryImpl) {
			namedQueryRepository = ((SessionFactoryImpl) sessionFactory).getNamedQueryRepository();
		}
		return namedQueryRepository;
	}
	/**
	 * 
	 * 说明：根据key 取得对应的NamedQueryDefinition
	 * @Title: getNamedQuery
	 * @See: {@link #getNamedQuery(String)}
	 * @author fuyp
	 * @param queryName queryName
	 * @return  NamedQueryDefinition
	 * @date: 2017年9月18日 下午4:32:33
	 */
	protected NamedQueryDefinition getNamedQuery(String queryName){
		NamedQueryRepository namedQueryRepository = getNamedQueryRepository();
		if (namedQueryRepository == null) {
			return null;
		}

		return namedQueryRepository.getNamedQueryDefinition(queryName);
	}
	/**
	 * 
	 * 说明：根据key 取得对应的NamedSQLQueryDefinition
	 * @Title: getNamedSQLQuery
	 * @See: {@link #getNamedSQLQuery(String)}
	 * @author fuyp
	 * @param queryName queryName
	 * @return  NamedQueryDefinition
	 * @date: 2017年9月18日 下午4:32:33
	 */
	protected NamedSQLQueryDefinition getNamedSQLQuery(String queryName){
		NamedQueryRepository namedQueryRepository = getNamedQueryRepository();
		if (namedQueryRepository == null) {
			return null;
		}

		return namedQueryRepository.getNamedSQLQueryDefinition(queryName);
	}
}
